package com.admin.filter;

import com.admin.vo.TokenInfo;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class SessionTokenFilter extends ZuulFilter {

  @Autowired
  private RestTemplate restTemplate;

  public String filterType() {
    return "pre";
  }

  public int filterOrder() {
    return 1;
  }

  public boolean shouldFilter() {
    return true;
  }

  public Object run() throws ZuulException {
    RequestContext currentContext = RequestContext.getCurrentContext();
    HttpServletRequest request = currentContext.getRequest();
    TokenInfo tokenInfo= (TokenInfo) request.getSession().getAttribute("token");

    if(tokenInfo!=null){
      String token=tokenInfo.getAccess_token();
      log.info("token333:{}",tokenInfo);
      if(tokenInfo.isExpire()){
        String oauthServiceUrl="http://gateway.test.com:8091/token/oauth/token";
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.setBasicAuth("admin","123456");

        MultiValueMap<String,String> params=new LinkedMultiValueMap<String,String>();
        params.add("grant_type","refresh_token");
        params.add("refresh_token",tokenInfo.getRefresh_token());

        HttpEntity<MultiValueMap> httpEntity=new HttpEntity<MultiValueMap>(params,httpHeaders);

        try{
          ResponseEntity<TokenInfo> newToken = restTemplate.exchange(oauthServiceUrl, HttpMethod.POST, httpEntity, TokenInfo.class);
          request.getSession().setAttribute("token",newToken.getBody().init());
          log.info("token12:{}",newToken.getBody());
          token=newToken.getBody().getAccess_token();
        }catch(Exception ex){
          currentContext.setSendZuulResponse(false);
          currentContext.setResponseStatusCode(500);
          currentContext.setResponseBody("{\"message\":\"refresh fail\"}");
          currentContext.getResponse().setContentType("application/json");
        }

      }
      currentContext.addZuulRequestHeader("Authorization","bearer "+token);
    }
    return null;
  }
}
